
```{r setup, include=FALSE}
stataexe <- "/Applications/Stata/StataSE.app/Contents/MacOS/stata-se"
knitr::opts_chunk$set(engine.path = list(stata=stataexe))
remove(list = ls())
library(rmarkdown)
knitr::opts_knit$set(root.dir = getwd())  # Set root directory to the working directory of the master file
getwd()
```

Packages
```{r packages, warning=FALSE, include=FALSE, message=FALSE, results='hide', cache=FALSE}
# libraries
set.seed(2023)
options( scipen=100, digits = 15, stringsAsFactors=FALSE );
# vector of libraries to be used
libs <- c("dplyr", "tidyr", "readstata13", "haven", "stringr", "nleqslv", "gdata", 
  "Statamarkdown", "formattable", "ggplot2", "viridis", "RColorBrewer", 
  "reshape2", "foreign", "readxl", "writexl", "rjson", "Matrix", "geodist", 
  "plm", "xts", "MASS", "pracma", "openxlsx", "readr", "data.table")
 #Install libraries in case they are not installed
for( i in length(libs)){ 
if( !(libs[i] %in% installed.packages()) ) install.packages( libs ) 
};

# load library
lapply( libs, require, character.only=TRUE ); #make sure every element is TRUE
```

1) Calculate bilateral trade flows between countries for all sectors.
2) Calculate calibration targets.
3) Calculate the share of value-added for each sector on each country
4) Calculate the input-output matrix shares for each country. 
5) Calculate the distances between all regions.
6) Calculate the distance elasticity and own-dummy coefficients for trade flows in services and agriculture.
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/1-WIOD_VA_shares_io_shares_distances.Rmd")
```

Calculate state-country bilateral flows for all sectors except services. 
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/2-State_country.Rmd")
```

Calculate state-state bilateral flows for all sectors except services and agriculture. 
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/3-State_state.Rmd")
```

Calculate state-state and state-country bilateral flows for services using a gravity system approach. 
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/4-Gravity_services.Rmd")
```

Calculate state-state bilateral flows for agriculture using a gravity system approach. 
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/5-Gravity_agriculture.Rmd")
```

1) Combine the results of the previous 5 scripts to obtain the final matrix of bilateral flows (for all sectors, for all regions) for years 2000-2007.
2) Calculate the share of value added in gross output for each US state, for each sector.
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/6-Matrices_VA_shares_states.Rmd")
```

1) Calculate employment levels by state-sector for year 2000 using BLS and CENSUS.
2) Calculate the 2000-2007 change in imports from China to the US and other advanced economies. To run a linear regression using the change of sector US imports from China as the dependent variable and the change of sector  advanced economies' imports from China as the independent variable. 
3) Compute the exposure measure of equation (16) from the manuscript.
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/7-Exposure.Rmd")
```

1) Compute the employment level for each state and sector in year 2000 using CBS data.
2) Compute the employment level for each state and sector in year 2000 and year 1999 using BLS data.
3) Compute the employment level for each country and sector in year 1999 and year 2000 using ILO and SEA data
4) Combine the previous outputs, and apply proportionality to ensure consistency with WIOD SEA
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/8-Employment_1999_2000.Rmd")
```

1) Compute ACS total state to state migration movements (knowing the sector of destination, but not the sector of origin), by year for 1999-2001.
2) Compute IRS total state to state migration movements (not knowing the sector of origin, nor the sector of destination), for 1999.
3) Compute CPS total state to state migration movements (knowing both the sector of origin and the sector of destination), by year for 1999-2001. 
4) Combine the data from the previous three steps to compute our final sector-state to sector-state mobility flows. Then we calculate the corresponding mobility shares in a case with migration and a case without migration (that is, not allowing state to state movements, just allowing sector reallocation).
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/9-Migration_matrix.Rmd")
#WARNING: Depending on the memory capacity of your computer, R may throw the error "cannot allocate vector of size ..." in the "Generate cps_nber yearly" chunk. However, the error will disappear (and you will still get the output) if you go to the script and run directly the code since the moment the error appeared on.
```

This file joins all the final data (except for the calibration targets) in a single file.
```{r, warning=FALSE, message = FALSE}
rmarkdown::render("codes/10-Joining_all.Rmd")
```
